//
//  UIApplication+LiftCycle.m
//  Y2EventBus
//
//  Created by harry.tong on 2021/6/21.
//

#import "UIApplication+LiftCycle.h"
#import <objc/runtime.h>
#import "Aspects.h"
#import "Y2Router.h"

@implementation UIApplication (LiftCycle)

+(void) load{
    SEL originalSelector = @selector(setDelegate:);
    SEL swizzledSelector = @selector(y2SetDelegate:);
    Method originalMethod = class_getInstanceMethod(self, originalSelector);
    Method swizzledMethod = class_getInstanceMethod(self, swizzledSelector);
    BOOL didAddMethod = class_addMethod(self, originalSelector, method_getImplementation(swizzledMethod), method_getTypeEncoding(swizzledMethod));
    if (didAddMethod) {
        class_replaceMethod(self, swizzledSelector, method_getImplementation(originalMethod), method_getTypeEncoding(originalMethod));
    }
    else {
        method_exchangeImplementations(originalMethod, swizzledMethod);
    }
}


-(void) y2SetDelegate:(id<UIApplicationDelegate>) delegate{
    unsigned count = 0;
    Method *methods = class_copyMethodList([delegate class], &count);
    for (int i = 0; i < count; i++) {
        Method method = methods[i];
        SEL sel = method_getName(method);
        struct objc_method_description methodDesc = protocol_getMethodDescription(@protocol(UIApplicationDelegate), sel, NO, YES);
        if (methodDesc.name != NULL && methodDesc.types != NULL) {
            [((NSObject *) delegate) aspect_hookSelector:sel withOptions:AspectPositionAfter usingBlock:^(id<AspectInfo> info) {
                [Y2Router applicationLiftCycleMethod:sel info:info];
            } error:nil];
        }
    }
    [self y2SetDelegate:delegate];
}

@end
